import React, { useState, useRef, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import styles from './AuthModal.module.css';

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const AuthModal: React.FC<AuthModalProps> = ({ isOpen, onClose }) => {
  const { login, signup, error: authError } = useAuth();
  const [isLogin, setIsLogin] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);
  const emailRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);
  const nameRef = useRef<HTMLInputElement>(null);

  // 重置表单状态
  useEffect(() => {
    if (!isOpen) {
      setError(null);
      setIsSubmitting(false);
      if (formRef.current) {
        formRef.current.reset();
      }
    }
  }, [isOpen]);

  // 显示错误信息
  useEffect(() => {
    if (authError) {
      setError(authError);
    }
  }, [authError]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;

    setIsSubmitting(true);
    setError(null);

    try {
      const email = emailRef.current?.value || '';
      const password = passwordRef.current?.value || '';

      if (isLogin) {
        await login(email, password);
      } else {
        const name = nameRef.current?.value || '';
        await signup(email, password, name);
      }
      onClose();
    } catch (err) {
      // 错误已在AuthContext中处理
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modal}>
      <div className={styles.modalContent}>
        <button 
          className={styles.closeButton}
          onClick={onClose}
          aria-label="关闭"
        >
          ×
        </button>
        
        <h2 className={styles.title}>
          {isLogin ? '登录' : '注册'}
        </h2>

        {error && (
          <div className={styles.errorMessage}>
            {error}
          </div>
        )}

        <form 
          ref={formRef}
          className={styles.form}
          onSubmit={handleSubmit}
          noValidate
        >
          <div className={styles.inputGroup}>
            <label htmlFor="email" className={styles.label}>
              邮箱
            </label>
            <input
              ref={emailRef}
              id="email"
              type="email"
              className={styles.input}
              required
              autoComplete="email"
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.inputGroup}>
            <label htmlFor="password" className={styles.label}>
              密码
            </label>
            <input
              ref={passwordRef}
              id="password"
              type="password"
              className={styles.input}
              required
              minLength={6}
              autoComplete={isLogin ? 'current-password' : 'new-password'}
              disabled={isSubmitting}
            />
          </div>

          {!isLogin && (
            <div className={styles.inputGroup}>
              <label htmlFor="name" className={styles.label}>
                用户名
              </label>
              <input
                ref={nameRef}
                id="name"
                type="text"
                className={styles.input}
                required
                minLength={2}
                autoComplete="name"
                disabled={isSubmitting}
              />
            </div>
          )}

          <button
            type="submit"
            className={styles.submitButton}
            disabled={isSubmitting}
          >
            {isSubmitting ? '处理中...' : (isLogin ? '登录' : '注册')}
          </button>
        </form>

        <div className={styles.switchMode}>
          {isLogin ? '还没有账号？' : '已有账号？'}
          <button
            type="button"
            className={styles.switchButton}
            onClick={() => setIsLogin(!isLogin)}
            disabled={isSubmitting}
          >
            {isLogin ? '注册' : '登录'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AuthModal; 